package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.cache.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/20 10:50
 * @Version 1.0
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private CacheService cacheService;


    public final static String CURRENT = "CURRENT_";
    public final static String FUTURE = "FUTURE_";

    @Override
    public Long addTask(Task task) {

        //保存数据库
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task,taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);

        task.setTaskId(taskinfo.getTaskId());

        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo,taskinfoLogs);
        taskinfoLogs.setVersion(TaskinfoLogs.VERSION_DEFAULT);
        taskinfoLogs.setStatus(TaskinfoLogs.STATUS_INIT);
        logsMapper.insert(taskinfoLogs);

        saveToCache(task);

        return task.getTaskId();
    }

    private void saveToCache(Task task){
        //存redis,key规则：  prefix-type-priority
        //获取预设时间：当前时间+预设时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        //执行时间小于等于当前时间，表示要立马执行，放到list
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(buildKey(CURRENT,task), JSON.toJSONString(task));
        }else if(System.currentTimeMillis() < calendar.getTime().getTime()){
            cacheService.zAdd(buildKey(FUTURE,task),JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    @Override
    public Task poll(Integer taskType, Integer priority) {
        String taskJson = cacheService.lRightPop(buildKey(CURRENT, taskType, priority));
        if(StringUtils.isEmpty(taskJson)){
            return null;
        }
        Task task = JSON.parseObject(taskJson, Task.class);

        //处理数据库，删除taskInfo ，修改log状态
        taskinfoMapper.deleteById(task.getTaskId());
        TaskinfoLogs taskinfoLogs = logsMapper.selectOne(Wrappers.<TaskinfoLogs>lambdaQuery().eq(TaskinfoLogs::getTaskId, task.getTaskId()));
        taskinfoLogs.setStatus(TaskinfoLogs.STATUS_EXECUTED);
        logsMapper.updateById(taskinfoLogs);

        return task;
    }

    /**
     *
     * 构造KEY
     * @param prefix
     * @param task
     * @return
     */
    private String buildKey(String prefix,Task task){
        return buildKey(prefix,task.getTaskType(),task.getPriority());
    }

    /**
     *
     * 构造KEY
     * @param prefix
     * @param type
     * @param priority
     * @return
     */
    private String buildKey(String prefix,Integer type,Integer priority){
        return prefix +type + "-" + priority;
    }


    @Scheduled(cron = "0 0 */5 * * ?")
    public void refreshSetToList(){
        log.info("开始执行未来数据刷新到list中");
        String key = "LOCK_KEY_FUTURE_TO_LIST";
        String token = cacheService.tryLock(key,30*1000);
        if(token == null){
            log.info("没获取到锁，不再执行");
            return;
        }
        log.info("本机获取到锁，执行任务");
        Set<String> futureKeys = cacheService.scan(FUTURE + "*");
        for (String futureKey : futureKeys) {
            //FUTURE_2_1
            //CURRENT_2_1
            log.info("处理当前的KEY：{}",futureKey);
            Set<String> needExecTasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
            if(CollectionUtils.isEmpty(needExecTasks)){
                log.info("当前Key:{}没有需要执行的任务",futureKey);
                continue;
            }
            //构造要执行任务list的key
            String currentKey = CURRENT + futureKey.split(FUTURE)[1];
            cacheService.refreshWithPipeline(futureKey,currentKey,needExecTasks);
            log.info("将future:{}中数据刷新到list中:{}",futureKey,needExecTasks);
        }
        log.info("任务执行完成");
    }


    @Scheduled(cron = "0 0 */4 * * ?")
    public void refreshDbtoZset(){
        log.info("开始执行数据库任务刷新到zset");
        String key = "LOCK_KEY_DB_TO_SET";
        String token = cacheService.tryLock(key,30*1000);
        if(token == null){
            log.info("没获取到锁，不再执行");
            return;
        }
        //删除缓存
        Set<String> currentKeys = cacheService.scan(CURRENT + "*");
        Set<String> futureKeys = cacheService.scan(FUTURE + "*");
        cacheService.delete(currentKeys);
        cacheService.delete(futureKeys);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if(CollectionUtils.isEmpty(taskinfos)){
            log.info("未来五分钟没有需要执行的任务");
            return;
        }

        for (Taskinfo taskinfo : taskinfos) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            saveToCache(task);
        }
        log.info("刷新了{}条数据到缓存",taskinfos.size());
    }


}